/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};


class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (!head) return nullptr;
        int n = 1;
        ListNode* curr = head;
        while (curr->next) {
            curr = curr->next;
            n++;  // 求出链表长度
        }
        curr->next = head;

        int pos = n - (k % n);  // 断开环的位置
        while (pos--) curr = curr->next;
        head = curr->next;
        curr->next = nullptr;
        return head;
    }

    // 更为友好的方法：快慢指针
    ListNode* rotateRight2(ListNode* head, int k) {
        if (!head) return head;

        // 计算链表长度
        int length = 0;
        ListNode* curr = head;
        while (curr) {
            length++;
            curr = curr->next;
        }

        k = k % length;
        if (k==0) return head;

        // 找切断点
        ListNode* slow = head, * fast = head;
        for (int i=0; i<k; i++) fast = fast->next;
        while (fast->next) {
            fast = fast->next;
            slow = slow->next;
        }
        ListNode* temp = slow->next;
        slow->next = nullptr;
        fast->next = head;
        return temp;
    }
};
